package com.atguigu.order.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.atguigu.order.bean.Order;
import com.atguigu.order.properties.OrderProperties;
import com.atguigu.order.service.impl.OrderServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

/**
 * @author fhs
 * Create by 2025/6/23 09:44
 */
//不能进行实时更新，设置@RefreshScope进行实时更新
//@RefreshScope//自动刷动功能会更加方便一点
//@RequestMapping("/api/order")//不加这个基本路径了，使用路由的路径重写
@RestController
@Slf4j
@CrossOrigin
public class OrderController {

    @Autowired
    private OrderServiceImpl orderServiceImpl;

    @Autowired
    OrderProperties orderProperties;
/*
    @Value("${order.timeout}")
    String orderTimeout;
    @Value("${order.auto-config}")
    String orderAutoConfig;*/

    /*@GetMapping("/config")
    public String config(){
        return "order.timeout=" + orderTimeout + ";order.auto-config=" + orderAutoConfig;
    }*/
    @GetMapping("/config")
    public String config() {
        return "order.timeout=" + orderProperties.getTimeOut() + ";order.auto-config="
                + orderProperties.getAutoConfig() + "order.dbUrl " +
                orderProperties.getDbUrl();
    }

    //创建订单
    @GetMapping("/create")
    public Order createOrder(@RequestParam("userId") Long userId,
                             @RequestParam("productId") Long productId) {
        Order order = orderServiceImpl.createOrder(productId, userId);
        return order;
    }

    //创建订单
    @GetMapping("/seckill")
    @SentinelResource(value = "seckill-order", fallback = "seckillFallback")
    public Order seckill(@RequestParam(value="userId",required = false) Long userId,
                         @RequestParam(value = "productId",defaultValue = "1000") Long productId) {
        Order order = orderServiceImpl.createOrder(productId, userId);
        order.setId(Long.MAX_VALUE);
        return order;
    }


    public Order seckillFallback(Long userId, Long productId, Throwable exception) {
        System.out.println("seckillFallback兜底回调将被调用......");
        Order order = new Order();
        order.setId(productId);
        order.setUserId(userId);
        order.setAddress("异常信息是：" + exception.getClass());
        return order;
    }

    @GetMapping("/writeDb")
    public String writeDb() {
        return "writeDb success......";
    }

    @GetMapping("/readDb")
    public String readDb() {
        log.info("readDb...");
        return "readDb success......";
    }
}
